<script setup lang="ts">
import { computed, h } from 'vue';
import { Card, Table, Tag } from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';

// 定义汇率数据类型
interface SpotRate {
  bid: number;
  ask: number;
  mid: number;
  lastUpdateTime?: string;
}

// 定义props
interface Props {
  spotPriceData?: Record<string, SpotRate>;
}

const props = withDefaults(defineProps<Props>(), {
  spotPriceData: () => ({})
});

// 格式化汇率
const formatRate = (rate: number) => {
  if (rate === null || rate === undefined) return '-';
  return rate.toFixed(6);
};

// 格式化价差
const formatSpread = (bid: number, ask: number) => {
  if (!bid || !ask) return '-';
  const spread = ask - bid;
  return `${spread.toFixed(6)} (${((spread / bid) * 100).toFixed(4)}%)`;
};

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  try {
    return new Date(dateStr).toLocaleString('zh-CN');
  } catch {
    return dateStr;
  }
};

// 获取汇率颜色
const getRateColor = (bid: number, ask: number) => {
  if (!bid || !ask) return 'default';
  const spread = ask - bid;
  const spreadPercent = (spread / bid) * 100;

  if (spreadPercent < 0.01) return 'green';
  if (spreadPercent < 0.05) return 'blue';
  if (spreadPercent < 0.1) return 'orange';
  return 'red';
};

// 获取汇率状态
const getRateStatus = (bid: number, ask: number) => {
  if (!bid || !ask) return '无数据';
  const spread = ask - bid;
  const spreadPercent = (spread / bid) * 100;

  if (spreadPercent < 0.01) return '极窄';
  if (spreadPercent < 0.05) return '正常';
  if (spreadPercent < 0.1) return '较宽';
  return '极宽';
};

// 表格数据
const rateTableData = computed(() => {
  if (!props.spotPriceData) return [];

  return Object.entries(props.spotPriceData).map(([pair, rate]) => ({
    key: pair,
    pair,
    bid: rate.bid,
    ask: rate.ask,
    mid: rate.mid,
    spread: rate.ask - rate.bid,
    spreadPercent: ((rate.ask - rate.bid) / rate.bid) * 100,
    lastUpdateTime: rate.lastUpdateTime
  }));
});

// 表格列定义
const rateColumns: TableColumnsType = [
  {
    title: '货币对',
    dataIndex: 'pair',
    key: 'pair',
    width: 120,
    fixed: 'left'
  },
  {
    title: '买价',
    dataIndex: 'bid',
    key: 'bid',
    width: 120,
    customRender: ({ text }) => formatRate(text as number),
    sorter: (a: any, b: any) => a.bid - b.bid
  },
  {
    title: '卖价',
    dataIndex: 'ask',
    key: 'ask',
    width: 120,
    customRender: ({ text }) => formatRate(text as number),
    sorter: (a: any, b: any) => a.ask - b.ask
  },
  {
    title: '中间价',
    dataIndex: 'mid',
    key: 'mid',
    width: 120,
    customRender: ({ text }) => formatRate(text as number),
    sorter: (a: any, b: any) => a.mid - b.mid
  },
  {
    title: '价差',
    dataIndex: 'spread',
    key: 'spread',
    width: 120,
    customRender: ({ text }) => formatRate(text as number),
    sorter: (a: any, b: any) => a.spread - b.spread
  },
  {
    title: '价差(%)',
    dataIndex: 'spreadPercent',
    key: 'spreadPercent',
    width: 100,
    customRender: ({ text }) => `${(text as number).toFixed(4)}%`,
    sorter: (a: any, b: any) => a.spreadPercent - b.spreadPercent
  },
  {
    title: '状态',
    key: 'status',
    width: 80,
    customRender: ({ record }) => {
      const color = getRateColor(record.bid, record.ask);
      const status = getRateStatus(record.bid, record.ask);
      return h(Tag, { color }, () => status);
    }
  },
  {
    title: '更新时间',
    dataIndex: 'lastUpdateTime',
    key: 'lastUpdateTime',
    width: 180,
    customRender: ({ text }) => formatDate(text as string)
  }
];
</script>

<template>
  <Card title="即期汇率" :bordered="false">
    <div v-if="!spotPriceData || Object.keys(spotPriceData).length === 0" class="empty-state">
      <div class="empty-text">暂无即期汇率数据</div>
    </div>
    <div v-else>
      <!-- 汇率概览 -->
      <div class="rate-overview">
        <div class="rate-grid">
          <div v-for="(rate, pair) in spotPriceData" :key="pair" class="rate-col">
            <Card size="small" class="rate-card">
              <div class="rate-header">
                <h4>{{ pair }}</h4>
                <Tag :color="getRateColor(rate.bid, rate.ask)">{{ getRateStatus(rate.bid, rate.ask) }}</Tag>
              </div>
              <div class="rate-content">
                <div class="rate-item">
                  <span class="label">买价:</span>
                  <span class="value bid">{{ formatRate(rate.bid) }}</span>
                </div>
                <div class="rate-item">
                  <span class="label">卖价:</span>
                  <span class="value ask">{{ formatRate(rate.ask) }}</span>
                </div>
                <div class="rate-item">
                  <span class="label">中间价:</span>
                  <span class="value mid">{{ formatRate(rate.mid) }}</span>
                </div>
                <div class="rate-item spread">
                  <span class="label">价差:</span>
                  <span class="value">{{ formatSpread(rate.bid, rate.ask) }}</span>
                </div>
              </div>
              <div v-if="rate.lastUpdateTime" class="rate-footer">
                <small>更新时间: {{ formatDate(rate.lastUpdateTime) }}</small>
              </div>
            </Card>
          </div>
        </div>
      </div>

      <!-- 详细表格 -->
      <div class="rate-table" style="margin-top: 24px">
        <h3>汇率详情</h3>
        <Table
          :columns="rateColumns"
          :data-source="rateTableData"
          :pagination="false"
          size="small"
          :scroll="{ x: 800 }"
        />
      </div>
    </div>
  </Card>
</template>

<style scoped>
.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-text {
  color: #999;
  font-size: 14px;
}

.rate-overview {
  margin-bottom: 24px;
}

.rate-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.rate-col {
  min-width: 0;
}

.rate-card {
  height: 100%;
  transition: all 0.3s ease;
}

.rate-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.rate-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.rate-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.rate-content {
  margin-bottom: 12px;
}

.rate-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding: 4px 0;
}

.rate-item.spread {
  border-top: 1px solid #f0f0f0;
  padding-top: 8px;
  margin-top: 8px;
}

.rate-item .label {
  font-size: 13px;
  color: #6b7280;
  font-weight: 500;
}

.rate-item .value {
  font-size: 14px;
  font-weight: 600;
  font-family: 'Monaco', 'Menlo', monospace;
}

.rate-item .value.bid {
  color: #dc2626;
}

.rate-item .value.ask {
  color: #059669;
}

.rate-item .value.mid {
  color: #2563eb;
}

.rate-footer {
  text-align: center;
  color: #9ca3af;
  border-top: 1px solid #f3f4f6;
  padding-top: 8px;
}

.rate-table h3 {
  margin-bottom: 16px;
  color: #1f2937;
  font-size: 16px;
  font-weight: 600;
}
</style>
